<template>
  <dv-full-screen-container>
    <div class="dashboard process-vsibility">
      <div class="header">
        <div class="quit-info">
          <div class="quit" @click="handleExit">退出</div>
        </div>
        <div class="title">
          <!-- <img src="./img/titleCockpit.png" alt="" > -->
        </div>
        <div class="info">
          <div class="info-date">
            {{ today.toLocaleString().replace(/\//g, "-") }} 星期{{
              days[today.getUTCDay()]
            }}
          </div>
          <img src="./img/q1.png" alt="" @click="fullscreenToggler"
            style="width: 30px; height: 30px; margin-right: 20px;cursor: pointer;" />
        </div>
      </div>
      <div class="head-selection" style="width: 850px">
        <!-- :range-separator="$t('cockpit.to')" -->
        <div class="selection-item">
          <div class="date-picker-box">
            <el-date-picker class="echarts-head-date" size="medium" v-model="dateRange" type="daterange"
              value-format="yyyy-MM-dd" format="yyyy年MM月dd日" @change="handleEchartDateChange" start-placeholder="开始日期"
              end-placeholder="结束日期" style="background-color: rgba(0, 17, 152, 0); width: 350px">
            </el-date-picker>
          </div>
        </div>
        <div class="selection-item">
          <el-select style="width: 220px" size="medium" v-model="queryParams.divisionIdList" placeholder="请选择事业部"
            :multiple="true" collapse-tags>
            <el-option v-for="(item, i) in deptList" :key="i" :label="item.divisionName" :value="item.divisionId">
            </el-option>
          </el-select>
        </div>
        <div class="selection-item">
          <el-select style="width: 220px" size="medium" v-model="queryParams.baseIdList" filterable clearable
            placeholder="请选择基地" :multiple="true" collapse-tags>
            <el-option v-for="(item, i) in factoryList" :key="i" :label="item.baseName" :value="item.baseId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="body" ref="body">
        <div class="body-left">
          <div class="dv-section">
            <div class="dv-title">
              <div class="title-info">
                <img src="./img/j6.png" />
                <span>{{ $t("cockpit3.incomingInspectionTaskList") }}</span>
              </div>
              <div class="title-bg">
                <img src="./img/j4.png" />
              </div>
            </div>
            <dv-scroll-board :config="config1" :style="{
              width: '100%',
              // height: `${(bodyHeight - 75) * 0.5}px`,
              height: '300px',
            }" @click="clickConfig1" />
          </div>
          <div class="dv-section mt5">
            <div class="dv-title">
              <div class="title-info">
                <img src="./img/j6.png" />
                <span>{{ $t("cockpit3.MRBList") }}</span>
              </div>
              <el-select size="medium" v-model="queryParams.ncrStatus" style="width: 120px;margin-right: 8px;">
                <el-option v-for="(item, i) in mrbStatus || []" :key="i" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <div class="title-bg">
                <img src="./img/j4.png" />
              </div>
            </div>
            <dv-scroll-board :config="config2" :style="{
              width: '100%',
              height: `300px`,
            }" @click="clickConfig2" />
          </div>
        </div>
        <div class="body-right">
          <div class="body-right-item">
            <div class="right-item-title">
              <div class="right-item-title-info">
                <span>{{ $t("cockpit3.checklist") }}</span>
              </div>
              <div class="right-item-title-bg">
                <img src="./img/j4.png" />
              </div>
            </div>
            <div class="echart-box" style="margin-bottom: 8px">
              <div ref="echart3" style="width: 100%; height: 100%"></div>
            </div>
          </div>
          <div class="body-right-item">
            <div class="right-item-title">
              <div class="right-item-title-info">
                <span>{{ $t("cockpit3.inspectionResult") }}</span>
              </div>
              <div class="right-item-title-bg">
                <img src="./img/j4.png" />
              </div>
            </div>
            <div class="echart-box" style="margin-bottom: 8px">
              <div ref="echart4" style="width: 100%; height: 100%"></div>
            </div>
          </div>
          <div class="body-right-item">
            <div class="right-item-title">
              <div class="right-item-title-info">
                <span>{{ $t("cockpit3.unqualifiedInspectionSheet") }}</span>
              </div>
              <div class="right-item-title-bg">
                <img src="./img/j4.png" />
              </div>
            </div>
            <div class="echart-box">
              <div ref="echart5" style="width: 100%; height: 100%"></div>
            </div>
          </div>

          <!-- ================ -->
        </div>
      </div>
    </div>
  </dv-full-screen-container>
</template>

<script>
import {
  inspectionTaskListApi,
  mrbListAPI,
  inspectionDecisionRate,
  inspectionCheckResultRatioAPI,
} from "@/api/inspectionManagement/inspectionManagement";
import {
  divisionList,
  divisionAndBaseListAPI,
} from "@/api/masterdata/division";
import mixins from "./mixins";
import { divisionRateByExtraAPI } from "../../api/inspectionManagement/inspectionManagement";

export default {
  name: "dashboard",
  dicts: [
    "AUDIT_TYPE",
    "NYIQC_NCR_DECISION",
    "ENVERSION_SHEET_STATUS",
    "NYIQC_MRB_STATUS",
  ],
  components: {},
  mixins: [mixins],
  data() {
    return {
      today: new Date(),
      days: ["日", "一", "二", "三", "四", "五", "六"],
      echart1Tag: "daterange",
      echart1Type: "daterange",
      curEchart1Type: null,
      echart2Date: null,
      echart2Type: "daterange",
      deptList: null,
      factoryList: [],
      dataMet: null,
      visibleEchart56: true,
      visible: false,
      visibleMrb: false,
      dataMrb: null,
      visibleStu: false,
      dataStu: null,
      visibleSup: false,
      dataSup: null,
      visibleMea: false,
      dataMea: null,
      bodyWidth: 0,
      bodyHeight: 0,
      multiple: false,
      clearable: false,
      queryParams: {
        divisionIdList: [],
        baseIdList: [],
        beginTime: null,
        endTime: null,
        ncrStatus: "1",
      },
      materialList: [],
      dateRange: [],
      config1: {
        header: [
          this.$t("inventoryManagement.arrivalTime"),
          this.$t("material.materialCode"),
          this.$t("material.materialName"),
          this.$t("inventoryManagement.purchaseDocument"),
          this.$t("bomControl.bomsupplier"),
          this.$t("inventoryManagement.inspectionOrderstatus"),
          this.$t("cockpit3.emergencyReleaseOrNot"),
        ],
        rowNum: 6,
        headerHeight: 50,
        // index: true,
        align: [
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
        ],
        columnWidth: [176, 176, 176, 176, 176, 176, 176],
        // headerBGC: '#0873DC',
        headerBGC: "transparent",
        oddRowBGC: "transparent",
        evenRowBGC: "transparent",
        data: undefined,
      },
      config2: {
        header: [
          this.$t("cockpit3.OAOrderNumber"),
          this.$t("public.title"),
          this.$t("inventoryManagement.purchaser"),
          this.$t("inspectionManagement.materialBatch"),
          this.$t("inspectionManagement.materialName"),
          this.$t("cockpit3.materialQuantity"),
          this.$t("cockpit3.reviewDecision"),
        ],
        rowNum: 7,
        headerHeight: 50,
        // index: true,
        align: [
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
          "center",
        ],
        columnWidth: [176, 176, 176, 176, 176, 176, 176],
        // headerBGC: '#0873DC',
        headerBGC: "transparent",
        oddRowBGC: "transparent",
        evenRowBGC: "transparent",
        data: undefined,
        inspectionTaskList: [],
        mrbList: [],
      },
    };
  },
  watch: {
    ["queryParams.divisionIdList"](val) {
      // 节流
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.factoryList = [];
        for (let i = 0; i < val.length; i++) {
          const divisionIdIndex = this.deptList.findIndex(
            (item) => item.divisionId === val[i]
          );
          if (divisionIdIndex !== -1) {
            this.deptList[divisionIdIndex].baseList.forEach((item) => {
              const isExist = this.factoryList.findIndex(
                (it) => it.baseId === item.baseId
              );
              if (isExist === -1) {
                this.factoryList.push(item);
              }
            });
            this.queryParams.baseIdList = [];
            this.queryParams.baseIdList[0] = this.factoryList[0]?.baseId;
          }
        }
      }, 500)

      // if (val) {
      //   this.listALL()
      // }
    },
    ["queryParams.baseIdList"](val) {
      // 节流
      if (this.timer1) {
        clearTimeout(this.timer1)
      }
      this.timer1 = setTimeout(() => {
        if (val && this.queryParams.divisionIdList) {
          this.listALL();
        }
      }, 500)
    },
    ["queryParams.ncrStatus"]() {
      mrbListAPI({
        divisionIdList: this.queryParams.divisionIdList.join(","),
        baseIdList: this.queryParams.baseIdList.join(","),
        ncrStatus: this.queryParams.ncrStatus,
        beginTime: this.queryParams.beginTime,
        endTime: this.queryParams.endTime,
      }).then((res) => {
        this.config2 = {
          ...this.config2,
          data: res.data.map((i) => {
            return [
              i.ncrProcessId,
              i.title,
              i.initiatorName,
              i.lot,
              i.materialName,
              i.batchAmount,
              this.formatCE_NCR(i.usingDecision),
              // i.id,
            ];
          }),
        };
        console.log(this.config2.data);
      });
    },
  },
  computed: {
    mrbStatus() {
      // 筛选已完成和处理中
      return this.dict.type.NYIQC_MRB_STATUS.filter((item) =>
        ["已完成", "处理中"].includes(item.label)
      );
    },
  },
  mounted() {
    this.domInit();
    this.initPage();
  },
  methods: {
    isFullscreen() {
      return (
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement
      );
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    },
    requestFullScreen(element) {
      if (!this.isFullscreen()) {
        // 检查是否已全屏，如果不是则进入全屏模式
        var requestMethod =
          element.requestFullScreen ||
          element.webkitRequestFullScreen ||
          element.mozRequestFullScreen ||
          element.msRequestFullScreen;
        if (requestMethod) {
          // 如果浏览器支持全屏API
          requestMethod.call(element);
        } else if (typeof window.ActiveXObject !== "undefined") {
          // 对于IE浏览器，可以使用ActiveXObject
          var wscript = new ActiveXObject("WScript.Shell");
          if (wscript !== null) {
            wscript.SendKeys("{F11}");
          }
        }
      } else {
        // 如果已全屏则退出全屏模式
        this.exitFullscreen();
      }
    },
    fullscreenToggler() {
      const elem = document.body; // 让整个body全屏
      this.requestFullScreen(elem);
    },
    clickConfig1(config) {
      debugger;
      var data = this.config1.data[config.rowIndex];
      console.log(data, config.rowIndex);
      this.$router.push({ path: "/incomingDetail/index/" + this.inspectionTaskList[config.rowIndex].id });
    },
    clickConfig2(config) {
      var data = this.config2.data[config.rowIndex];
      this.$router.push({
        path: "/inventory/mrbReview/" + this.mrbList[config.rowIndex].id + "?viewType=3",
      });
    },
    async listALL() {
      this.initChart();
    },
    domInit() {
      // const self = this;
      // /** 监听文本框内容高度*/
      // const observer = new ResizeObserver((entries) => {
      //   entries.forEach((entry) => {
      //     const cr = entry.contentRect;
      //     self.bodyWidth = cr.width;
      //     self.bodyHeight = cr.height;
      //   });
      // });
      // observer.observe(this.$refs.body);
    },
    handleEchartDateChange(e) {
      this.queryParams = {
        ...this.queryParams,
        beginTime: e ? e[0] : undefined,
        endTime: e ? e[1] : undefined,
      };
    },
    handleExit() {
      window.opener = null;
      window.open("", "_self");
      window.close();
      this.$router.go(-1);
    },
    async initPage() {
      //事业部门
      await divisionAndBaseListAPI().then((res) => {
        this.deptList = res;
        this.queryParams.divisionIdList.push(res[0]?.divisionId);
      });
    },

    formatCE_NCR(e) {
      if (e) {
        let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
          return item.value === e;
        });
        if (obj) {
          return obj.label;
        } else {
          return "";
        }
      } else {
        return "";
      }
    },

    formatOrderStatus(e) {
      if (e) {
        let obj = this.dict.type.ENVERSION_SHEET_STATUS.find((item) => {
          return item.value === e;
        });
        if (obj) {
          return obj.label;
        } else {
          return "";
        }
      } else {
        return "";
      }
    },
    handleQueryEchart3() {
      divisionRateByExtraAPI(this.queryParams).then(
        (res) => {
          this.initChart3(res.data || []);
        },
        (err) => {
          this.initChart3([]);
        }
      );
    },
    handleQueryEchart4() {
      inspectionCheckResultRatioAPI(this.queryParams).then(
        (res) => {
          this.initChart4(res.data.inspectionRatioList || []);
        },
        (err) => {
          this.initChart4([]);
        }
      );
    },
    handleQueryEchart5() {
      inspectionDecisionRate(this.queryParams).then(
        (res) => {
          this.initChart5(res.data || []);
        },
        (err) => {
          this.initChart5([]);
        }
      );
    },
    initChart() {
      if (this.dateRange !== null && this.dateRange.length) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
      inspectionTaskListApi(this.queryParams).then((res) => {
        this.config1 = {
          ...this.config1,
          data: res.data.map((i) => {
            return [
              i.cputime,
              i.materialCode,
              i.materialName,
              i.ebeln,
              i.supplierName,
              this.formatOrderStatus(i.sheetStatus),
              i.release,
              // i.id,
            ];
          }),
        };
        this.inspectionTaskList=res.data
      });

      // MRB清单
      mrbListAPI({
        divisionIdList: this.queryParams.divisionIdList.join(","),
        baseIdList: this.queryParams.baseIdList.join(","),
        ncrStatus: this.queryParams.ncrStatus,
        beginTime: this.queryParams.beginTime,
        endDate: this.queryParams.endTime,
      }).then((res) => {
        this.config2 = {
          ...this.config2,
          data: res.data.map((i) => {
            return [
              i.ncrProcessId,
              i.title,
              i.initiatorName,
              i.lot,
              i.materialName,
              i.batchAmount,
              this.formatCE_NCR(i.usingDecision),
              // i.id,
            ];
          }),
        };
        this.mrbList = res.data
        console.log(this.config2.data);
      });
      //echart3
      this.handleQueryEchart3();

      //echart4
      this.handleQueryEchart4();

      //echart5
      this.handleQueryEchart5();
    },
  },
};
</script>

<style scoped src="./index.scss" lang="scss"></style>
